import React, { useState, useEffect, useRef, useCallback } from 'react';
import styles from './index.module.scss';
import { ICON_PATHS } from '@/assets/images/constants';
import { Image } from '@douyinfe/semi-ui';
import { Dropdown, Menu } from '@arco-design/web-react';
import { IconDelete } from '@arco-design/web-react/icon';

const CustomAudioPlayer = ({
  src,
  title = '未命名音频',
  progressHeight = 6, // 新增：进度条高度
  progressBgColor, // 新增：进度条背景色
  showVolumeControl = true, // 新增：控制音量显示
  showELseControl = true, // 新增：控制更多操作菜单显示
  showTitle = true, // 新增：控制标题显示
  showTime = true, // 新增：控制时间显示
  onPlay, // 新增：播放事件回调
  onPause, // 新增：暂停事件回调
  onEnded, // 新增：播放结束事件回调
  onVolumeChange, // 新增：音量改变事件回调
  onSeek, // 新增：进度改变事件回调
  onOtherAction, // 新增：其他操作事件回调
}) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(80);
  const [isMuted, setIsMuted] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [bufferedProgress, setBufferedProgress] = useState(0);
  const [showOtherActions, setShowOtherActions] = useState(false); // 新增：控制其他操作显示

  const audioRef = useRef(null);
  const animationFrameRef = useRef(null); // 新增：用于requestAnimationFrame
  const lastUpdateTimeRef = useRef(0);
  const otherActionsRef = useRef(null); // 新增：其他操作菜单引用
  const [isDragging, setIsDragging] = useState(false); // 新增：追踪拖动状态

  // 初始化和监听音频事件
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    const handleLoadedMetadata = () => {
      setDuration(audio.duration);
    };

    // 新增：监听加载事件
    const handleLoadStart = () => {
      setIsLoading(true);
    };

    const handleCanPlayThrough = () => {
      setIsLoading(false);
    };

    // 新增：监听缓冲事件
    const handleProgress = () => {
      if (audio.buffered.length > 0) {
        const bufferedEnd = audio.buffered.end(audio.buffered.length - 1);
        const duration = audio.duration;
        if (duration > 0) {
          setBufferedProgress((bufferedEnd / duration) * 100);
        }
      }
    };

    // 新增：监听播放结束事件
    const handleEnded = () => {
      setIsPlaying(false);
      if (onEnded) onEnded();
    };

    audio.addEventListener('loadedmetadata', handleLoadedMetadata);
    audio.addEventListener('loadstart', handleLoadStart);
    audio.addEventListener('canplaythrough', handleCanPlayThrough);
    audio.addEventListener('progress', handleProgress);
    audio.addEventListener('ended', handleEnded); // 新增：添加播放结束事件监听

    return () => {
      audio.removeEventListener('loadedmetadata', handleLoadedMetadata);
      audio.removeEventListener('loadstart', handleLoadStart);
      audio.removeEventListener('canplaythrough', handleCanPlayThrough);
      audio.removeEventListener('progress', handleProgress);
      audio.removeEventListener('ended', handleEnded); // 新增：移除播放结束事件监听
    };
  }, [onEnded]);

  // 新增：音量控制逻辑
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    audio.volume = isMuted ? 0 : volume / 100;
    audio.muted = isMuted;
    if (onVolumeChange) onVolumeChange({ volume: audio.volume, isMuted });
  }, [volume, isMuted, onVolumeChange]);

  // 调整进度更新逻辑，考虑拖动状态
  const updateProgressSmoothly = useCallback(() => {
    const audio = audioRef.current;
    if (!audio || !isPlaying || isDragging) return; // 拖动时暂停自动更新

    const now = Date.now();
    // 限制更新频率，但使用requestAnimationFrame保持视觉流畅
    if (now - lastUpdateTimeRef.current > 50) {
      // 大约20fps
      setCurrentTime(audio.currentTime);
      lastUpdateTimeRef.current = now;
    }

    // 继续请求下一帧
    animationFrameRef.current = requestAnimationFrame(updateProgressSmoothly);
  }, [isPlaying, isDragging]);

  // 新增：在播放状态变化时控制动画帧请求
  useEffect(() => {
    if (isPlaying) {
      updateProgressSmoothly();
    } else if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current);
    }

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    };
  }, [isPlaying, updateProgressSmoothly]);

  // 新增：点击外部关闭其他操作菜单
  useEffect(() => {
    const handleClickOutside = event => {
      if (otherActionsRef.current && !otherActionsRef.current.contains(event.target)) {
        setShowOtherActions(false);
      }
    };

    if (showOtherActions) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showOtherActions]);

  // 播放/暂停切换
  const togglePlay = () => {
    const audio = audioRef.current;
    if (!audio) return;

    if (isPlaying) {
      audio.pause();
      if (onPause) onPause();
    } else {
      audio.play().catch(err => {
        console.error('播放失败:', err);
        setIsPlaying(false);
      });
      if (onPlay) onPlay();
    }
    setIsPlaying(!isPlaying);
  };

  // 调整进度 - 添加平滑动画效果
  const handleSeek = useCallback(
    e => {
      const audio = audioRef.current;
      if (!audio) return;

      const newTime = parseFloat(e.target.value);
      // 立即更新UI，不等待音频响应
      // 修复：确保时间不会小于0
      const clampedTime = Math.max(0, newTime);
      setCurrentTime(clampedTime);
      audio.currentTime = clampedTime;
      if (onSeek) onSeek(clampedTime);
    },
    [onSeek]
  );

  // 新增：点击进度条直接跳转
  const handleProgressClick = useCallback(
    e => {
      const audio = audioRef.current;
      if (!audio || !duration || isDragging) return;

      const rect = e.currentTarget.getBoundingClientRect();
      const clickPosition = e.clientX - rect.left;
      const percent = clickPosition / rect.width;
      const newTime = percent * duration;
      // 修复：确保时间不会小于0
      const clampedTime = Math.max(0, newTime);

      setCurrentTime(clampedTime);
      audio.currentTime = clampedTime;
      if (onSeek) onSeek(clampedTime);
    },
    [duration, isDragging, onSeek]
  );

  // 新增：拖动开始处理
  const handleSeekStart = useCallback(() => {
    setIsDragging(true);
    // 拖动开始时可以暂停动画帧更新
    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current);
    }
  }, []);

  // 新增：拖动结束处理
  const handleSeekEnd = useCallback(() => {
    setIsDragging(false);
    // 拖动结束后，如果正在播放，重新启动动画帧更新
    if (isPlaying) {
      updateProgressSmoothly();
    }
  }, [isPlaying, updateProgressSmoothly]);

  // 新增：处理其他操作
  const handleOtherAction = (action, src) => {
    setShowOtherActions(false);
    if (onOtherAction) onOtherAction(action, src);
  };

  // 格式化时间
  const formatTime = seconds => {
    if (isNaN(seconds)) return '00:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 计算进度百分比
  const progressPercentage = duration > 0 ? (currentTime / duration) * 100 : 0;

  // 构建进度条内联样式 - 移除data-hover-height属性，改用JavaScript控制悬停效果
  const progressWrapperStyle = {
    height: `${progressHeight}px`,
    backgroundColor: progressBgColor || 'rgba(255, 255, 255, 0.1)',
  };

  const dropList = (
    <Menu className={styles.audioDropdownMenu}>
      <Menu.Item
        style={{ width: 120 }}
        className={styles.dropdownMenuItem}
        onClick={() => handleOtherAction('delete', src)}>
        <IconDelete fontSize={16}/>
        删除
      </Menu.Item>
    </Menu>
  );

  // 移除进度条悬停高度计算

  return (
    <div className={styles.audioPlayer}>
      {/* 隐藏的音频元素 */}
      <audio ref={audioRef} src={src} preload="metadata" />

      {/* 控制区域 */}
      <div className={styles.controls}>
        {/* 播放/暂停按钮 */}
        <button
          className={`${styles.playButton} ${isLoading && styles.loading}`}
          onClick={togglePlay}
          aria-label={isPlaying ? '暂停' : '播放'}
          disabled={isLoading}>
          {isLoading ? (
            '⏳'
          ) : isPlaying ? (
            <Image
              src={ICON_PATHS.PAUSED_ICON}
              alt="暂停"
              width={24}
              height={24}
              draggable={false}
              preview={false}
            />
          ) : (
            <Image
              src={ICON_PATHS.PLAY_ICON}
              alt="播放"
              width={24}
              height={24}
              draggable={false}
              preview={false}
            />
          )}
        </button>
        {/* 时间显示 */}
        {showTime && (<div className={styles.timeDisplay}>
          <span>{formatTime(currentTime)}</span>
            {/* <span>{formatTime(duration)}</span> */}
          </div>
        )}

        {/* 音频标题 */}
        {showTitle && (
          <div className={styles.audioTitle} title={title}>
            {title}
          </div>
        )}

        {/* 进度条容器 - 包含缓冲进度和当前进度 */}
        <div className={styles.progressContainer}>
          <div
            className={styles.progressWrapper}
            style={progressWrapperStyle}
            onClick={handleProgressClick}>
            {/* 缓冲进度条 */}
            <div className={styles.bufferedProgress} style={{ width: `${bufferedProgress}%` }} />
            {/* 当前进度条 */}
            <div className={styles.currentProgress} style={{ width: `${progressPercentage}%` }} />
            {/* 拖动滑块 */}
            <div
              className={styles.progressHandle}
              style={{
                left: `${progressPercentage}%`,
                opacity: isDragging ? 1 : undefined, // 拖动时始终显示滑块
                transform: isDragging ? 'translate(-50%, -50%) scale(1.3)' : undefined, // 拖动时应用放大效果
              }}
            />
            {/* 隐藏的输入框用于拖动 */}
            <input
              type="range"
              className={styles.progressSlider}
              min="0"
              max={duration || 100}
              value={currentTime}
              onChange={handleSeek}
              onMouseDown={handleSeekStart} // 新增：监听拖动开始
              onMouseUp={handleSeekEnd} // 新增：监听拖动结束
              onTouchStart={handleSeekStart} // 新增：支持触摸屏
              onTouchEnd={handleSeekEnd} // 新增：支持触摸屏
              disabled={!duration}
            />
          </div>
        </div>

        {/* 时间显示 */}
        {showTime && (<div className={styles.timeDisplay}>
            {/* <span>{formatTime(currentTime)}</span> */}
            <span>{formatTime(duration)}</span>
          </div>
        )}

        {/* 音量控制 - 可通过props控制显示 */}
        {showVolumeControl && (
          <div className={styles.volumeControl}>
            <button
              className={styles.muteButton}
              onClick={() => setIsMuted(!isMuted)}
              aria-label={isMuted ? '取消静音' : '静音'}>
              {isMuted ? '🔇' : '🔊'}
            </button>
            <input
              type="range"
              className={styles.volumeSlider}
              min="0"
              max="100"
              value={isMuted ? 0 : volume}
              onChange={e => setVolume(parseFloat(e.target.value))}
            />
          </div>
        )}

        {/* 新增：其他操作按钮 */}
        {showELseControl && (
          // <div className={styles.otherActions} ref={otherActionsRef}>
          //   <button
          //     className={styles.otherActionsButton}
          //     onClick={() => setShowOtherActions(!showOtherActions)}
          //     aria-label="其他操作">
          //     <Image
          //       src={ICON_PATHS.MORE_ICON}
          //       alt="更多操作"
          //       width={24}
          //       height={24}
          //       draggable={false}
          //       preview={false}
          //     />
          //   </button>
          //   {/* 其他操作菜单 */}
          //   {showOtherActions && (
          //     <div className={styles.otherActionsMenu}>
          //       <button onClick={() => handleOtherAction('delete')}>删除</button>
          //       {/* <button onClick={() => handleOtherAction('loop')}>循环播放</button>
          //       <button onClick={() => handleOtherAction('report')}>举报</button> */}
          //     </div>
          //   )}
          // </div>
          <Dropdown droplist={dropList} position="br" trigger="click">
            <button
              className={styles.otherActionsButton}
              onClick={() => setShowOtherActions(!showOtherActions)}
              aria-label="其他操作">
              <Image
                src={ICON_PATHS.MORE_ICON}
                alt="更多操作"
                width={24}
                height={24}
                draggable={false}
                preview={false}
              />
            </button>
          </Dropdown>
        )}
      </div>
    </div>
  );
};

export default CustomAudioPlayer;
